package com.tanhua.server.service;


import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.CommentVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author anshuai
 * @create 2021-02-01 20:59
 */
@Service
public class CommentsService {

    @Reference
    private CommentApi commentApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MovementsMQService mqService;

    /**
     * 单条动态的评论列表
     *
     * @param movementId 动态id
     * @param page       当前页码
     * @param pagesize   每页几条
     * @return
     */
    public ResponseEntity findCommentList(String movementId, int page, int pagesize) {
        //1. 查询动态的评论列表
        PageResult<Comment> pageResult = commentApi.findCommentList(movementId, page, pagesize);

        //2.转换vo
        List<Comment> commentList = pageResult.getItems();
        List<CommentVO> voList = new ArrayList<>();
        for (Comment comment : commentList) {
            CommentVO vo = new CommentVO();

            //把评论的数据封装到vo
            BeanUtils.copyProperties(comment, vo);
            vo.setId(comment.getId().toHexString());
            //  yyyy年MM月dd日 HH:mm
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(new Date(comment.getCreated()));
            vo.setCreateDate(dateStr);

            //把评论者的数据封装到vo
            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            BeanUtils.copyProperties(userInfo, vo);

            //当前用户是否对这条评论点赞了
            Boolean hasLike = redisTemplate.hasKey("comment_like_" + UserHolder.getUserId() + "_" + comment.getId().toHexString());
            vo.setHasLiked(hasLike ? 1 : 0);

            //将数据添加到准备好的集合中
            voList.add(vo);
        }

        //3.构造返回值
        PageResult<CommentVO> result = new PageResult<>();
        BeanUtils.copyProperties(pageResult, result);
        result.setItems(voList);

        return ResponseEntity.ok(result);
    }

    /**
     * 单条动态-发表评论
     *
     * @param movementId 动态id
     * @param content    评论内容
     * @return
     */
    public ResponseEntity saveComment(String movementId, String content) {

        //1.补全数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(2);
        comment.setUserId(UserHolder.getUserId());
        comment.setPubType(1);
        comment.setContent(content);

        //设置被评论的用户
        Publish publish = publishApi.findById(movementId);
        comment.setPublishUserId(publish.getUserId());

        //保存评论
        commentApi.save(comment);

        //   给大数据推荐系统发送消息
        mqService.commentPublishMessage(movementId);

        return ResponseEntity.ok(null);
    }

    /**
     * 评论-点赞
     * @param commentId 评论id
     * @return
     */
    public ResponseEntity likeComment(String commentId) {

        //1.获取当前用户的id
        Long userId = UserHolder.getUserId();

        //2.封装数据Comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));
        //设置评论类型为点赞
        comment.setCommentType(1);
        //设置评论内容类型为评论
        comment.setPubType(3);
        comment.setUserId(userId);

        //设置被评论的用户
        Comment commentUser = commentApi.findById(commentId);
        comment.setPublishUserId(commentUser.getPublishUserId());

        //3.保存评论数据
        long count = commentApi.saveComment(comment);

        //4. 把点赞记录存储到Redis里
        redisTemplate.opsForValue().set("comment_like_" + userId + "_" + commentUser.getId().toHexString(),"1");

        return ResponseEntity.ok(count);
    }

    /**
     * 评论-取消点赞
     * @param commentId 评论id
     * @return
     */
    public ResponseEntity disLikeComment(String commentId) {
        //1. 调用API，把之前保存的Comment删除掉，得到最新计数
        //1.2 准备删除的条件：{userId: 130, publishId: xxxx, commentType: 1}
        Comment comment = new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(1);
        comment.setPublishId(new ObjectId(commentId));

        //调用APi,删除Comment数据
        long count = commentApi.removeComment(comment);

        //查询评论id,删除redis的记录用
        Comment commentUser = commentApi.findById(commentId);

        //2.从redis中删除之前的点赞记录
        redisTemplate.delete("comment_like_" + UserHolder.getUserId() + "_" + commentUser.getId().toHexString());

        //返回最新点赞数
        return ResponseEntity.ok(count);
    }
}
